﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.RolePremiss;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.RolePremiss
{
    public class CreateRolePremissHandler : IRequestHandler<CreateRolePremissCommon, ApiResult<int>>
    {
        private readonly IBaseRepository<RolePermissModel> rolepermissRepo;

        public CreateRolePremissHandler(IBaseRepository<RolePermissModel> rolepermissRepo)
        {
            this.rolepermissRepo = rolepermissRepo;
        }
       
        public async Task<ApiResult<int>> Handle(CreateRolePremissCommon request, CancellationToken cancellationToken)
        {

            ApiResult<int> res = new ApiResult<int>();

            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var result = rolepermissRepo.GetAll().Where(x=>x.RoleId==request.RoleId).ToList();
                await rolepermissRepo.Del(result);
                List<RolePermissModel> models = new List<RolePermissModel>();

                foreach (var item in request.MenuId)
                {
                    models.Add(new RolePermissModel()
                    {
                        MenuId = item,
                        RoleId = request.RoleId,
                        
                    });

                }
                int count=await rolepermissRepo.AddAll(models);
                if (count>0)
                {
                    res.Code=ApiEnum.Success;
                    res.Message = "分配成功";
                  
                }
                else
                {
                    res.Code = ApiEnum.Error;
                    res.Message = "分配失败";
                }

                tran.Complete();
                return await Task.FromResult(res);
            }

        }
    }
}
